<?php

namespace app\admin\controller\order;

use app\admin\model\Admin;
use app\admin\model\lnventory\Data;
use app\admin\model\lnventory\Details;
use app\admin\model\Preproduct;
use app\admin\model\Storage;
use app\common\controller\Backend;
use think\Db;
use think\Session;

/**
 * 
 *
 * @icon fa fa-circle-o
 */
class Order extends Backend
{
    
    /**
     * Order模型对象
     * @var \app\admin\model\Order
     */
    protected $model = null;
    protected $Orderitem = null;
    protected $Orderlog = null;
    protected $Githouse = null;
    protected $searchFields = "id,nb";
    protected $modelValidate = true;
    protected $modelSceneValidate = true;

    public function _initialize()
    {
        parent::_initialize();
        //Orderlog  Orderitem Githouse
        $this->model = new \app\common\model\order\Order;
        $this->Orderitem = new \app\common\model\order\Orderitem;
        $this->Orderlog = new \app\common\model\order\Orderlog;
        $this->Githouse = new \app\admin\model\Githouse;
    }
    
    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
//        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax())
        {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField'))
            {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                    ->where($where)
                    ->order($sort, $order)
                    ->count();
            $list = $this->model
                    ->where($where)
                    ->order($sort, $order)
                    ->limit($offset, $limit)
                    ->select();
            $list = collection($list)->toArray();
            $result = array("total" => $total, "rows" => $list);
            return json($result);
        }
        $this->view->assign('dep_id',$this->auth->department);
        return $this->view->fetch();
    }


    /**
     * 分公司 订单列表
     * @return string|\think\response\Json
     * @throws \think\Exception
     */
    public function company()
    {
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax())
        {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField'))
            {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                ->where($where)
                ->order($sort, $order)
                ->count();
            $list = $this->model
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();
            $list = collection($list)->toArray();
            $result = array("total" => $total, "rows" => $list);
            return json($result);
        }

        $this->view->assign('dep_id',$this->auth->department);
        return $this->view->fetch();
    }

    /**
     * 详情
     * @param $ids
     * @return string
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function detail($ids)
    {
        if($order = $this->model->get($ids))
        {
            $Githouse = $this->Githouse->get($order->githouse_id);
            //订单详情
            $orderList = $this->Orderitem->alias('a')
                ->field('a.*,a.remark as remarks,b.type,b.cname,b.b_n')
                ->where('a.order_id',$ids)
                ->join('hdyj_preproduct b','a.preproduct_id = b.id')
//                ->join('hdyj_order c ','a.order_id = c.id')
//                ->join('hdyj_githouse d','c.githouse_id = d.id')
                ->select();
            $order = $order->toArray();
            $order['userid_text'] = Admin::userName($order['userid']);
            $orderlogList = $this->Orderlog->where('order_id',$ids)->select();
            $this->view->assign('orderlogList',$orderlogList);
            //剩余发货 出库
            $orderLists = $this->Orderitem->alias('a')
                ->field('a.*,a.nums,a.remark as remarks,b.type,b.cname,b.b_n,b.bcp')
                ->where('a.order_id',$ids)
                ->where('a.num > a.nums')
                ->join('hdyj_preproduct b','a.preproduct_id = b.id')
                ->select();
            $this->view->assign('orderLists',$orderLists->toArray());
            //查询所有的仓库
            $storageList = Storage::with('department')->column('name','depid');
            //查询发货记录
            $detailsList = Details::where('order_id',$order['id'])->select()->toArray();
            if($detailsList)
            {
                foreach ($detailsList as &$item)
                {
                    $item['list'] = Data::alias('a')
                        ->field('a.num,b.cname')
                        ->where('a.lnventory_id',$item['id'])
                        ->join('hdyj_preproduct b','a.preproduct_id = b.id')
                        ->select()
                        ->toArray();
                }
            }
            $this->view->assign('detailsList',$detailsList);
            $this->view->assign('storageList',$storageList);
            $this->view->assign('second',$this->request->request('second',0));
            $this->view->assign('Githouse',$Githouse);
            $this->view->assign('order',$order);
            $this->view->assign('orderList',$orderList->toArray());
        }
        return $this->view->fetch();
    }

    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : true) : $this->modelValidate;
                        $this->model->validate($validate);
                    }

                    if($params['goods']['goods_id'][0])
                    {
                        $params['dep_id'] = $this->auth->department;
                        $params['userid'] = $this->auth->userid;
                        $params['deliverydate'] = time($params['deliverydate']);
                        unset($params['goods_ids'],$params['type']);
                        $result = $this->model->allowField(true)->save($params);
                        $orderId = $this->model->getLastInsID();
                        $orderItem = [];
                        foreach ($params['goods']['goods_id'] as $index=>$value)
                        {
                            $orderItem[] = [
                                'preproduct_id' => $value,
                                'num' => $params['goods']['goods_num'][$index],
                                'remark' => $params['goods']['remark'][$index],
                                'order_id' => $orderId,
                            ];
                        }
                    }else{
                        $this->error('请选择要货商品！');
                    }
                    //生产订单详情
                    $orderItemRes = $this->Orderitem->saveAll($orderItem,false);
                    if ($result !== false && $orderItemRes !== false) {
                        //添加操作日志
                        $this->Orderlog->create([
                            'order_id'=>$orderId,
                            'dep_name'=>$this->auth->department_text,
                            'dep_id'=>$this->auth->department,
                            'userid'=>$this->auth->userid,
                            'username'=>$this->auth->username,
                            'content'=>'已提交订货单，等待订货单审核',
                            'type'=>1,
                        ]);
                        $this->success();
                    } else {
                        $this->error($this->model->getError());
                    }
                } catch (\think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        //默认收货地址列表
        $githouse =  $this->Githouse->get(function ($query){
            $query->where('dep',Session::get('admin.department'))->where('default',1);
        });
        $this->view->assign('admin',Session::get('admin'));
        $this->view->assign('Githouse',$githouse);
        return $this->view->fetch();
    }

    /**
     * 出库
     */
    public function Outstock()
    {
        $param = $this->request->request('row/a');
        // 启动事务
        Db::startTrans();
        $Details = Details::create(['dep_id'=>$param['dep_id'],'order_id'=>$param['order_id'],'type'=>1,'nb'=>getOrderNo('L-')]);
        if(!$Details)
        {
            //回滚
            Db::rollback();
            $this->error();
        }
        $DetailsId = $Details->getLastInsID();
        //type =1 要货出库  2 要货入库
        foreach ($param['orderitem'] as $value)
        {
            $row = $this->Orderitem->get($value['id']);
            $row->nums += $value['nums'];//出库数量
            $result = $row->save();
            if(!$result)
            {
                //回滚
                Db::rollback();
                $this->error();
            }
            //成品出库存  减总部库存
            if($param['storage'] == 1)
            {
                if($value['type'] == 2)
                {
                    //减去成品库存
                    $result = Preproduct::where(['id'=>['in',$value['bcp']]])->setDec('storenum',$value['nums']);
                }else{
                    //减去半成品库存
                    $result = Preproduct::where('id',$value['preproduct_id'])->setDec('storenum',$value['nums']);
                }
                if(!$result)
                {
                    //回滚
                    Db::rollback();
                    $this->error();
                }
            }else{
                //减 分公司库存
                if($value['type'] == 2)
                {
                    //成品库存
                    $result = Storage::where('depid',$param['storage'])->where(['shopid'=>['in',$value['bcp']]])->setDec('stock',$value['nums']);
                }else{
                    //半成品库存
                    $result = Storage::where('depid',$param['storage'])->where('shopid',$value['preproduct_id'])->setDec('stock',$value['nums']);
                }
                if(!$result)
                {
                    //回滚
                    Db::rollback();
                    $this->error();
                }
            }
            //生成出库单详情
            $dataResult = Data::create([
                'preproduct_id'=>$value['preproduct_id'],
                'num'=>$value['nums'],
                'lnventory_id'=>$DetailsId,
            ]);
            if(!$dataResult)
            {
                //回滚
                Db::rollback();
                $this->error();
            }
            //查询是否发货完成   修改状态
        }
        // 提交事务
        Db::commit();
        $this->success();

    }


    /**  0              0->1          1->2           2->3
     * 会务下单 -> 审核[  领导审核 -> 客户管理部审核 -> ]->完成
     * status = -1  订单作废  deliverystatus = -1   不查询出来
     * status = 0  订单待审核(分公司审核) ->[1,2,3]
     * status = 1 订单审核通过    审核通过后不可以修改数据
     * status = 2 发货审核通过 填写物流信息
     * status = 3 订单完成
     *
     * deliverystatus = 0 备货中\代发货  如果 stauts=1  就可以操作发货  否则不能发货
     * deliverystatus = 1 已发货\待审核\发货已完成 (发完全部去货) (填写物流信息)  待审核
     * deliverystatus = 2 已发货\待审核\发货未完成 (发完一部分货) (填写物流信息)  待审核
     * deliverystatus = 3 确认收货\已完成
     *
     *
     * @param null $ids
     */
    //审核订单status=2  作废订单status=1   添加操作记录
    public function status($ids=null)
    {
        if($this->request->isAjax())
        {
            $status = $this->request->request('status');
            $row = $this->model->get($ids);
            if($status == 2)
            {
                //作废订单
                $row->status = -1;
                $row->deliverystatus = -1;
                $result = $row->save();
            }
            if($status == 1)
            {
                //审核通过
                $row->status = 1;
                $result = $row->save();
            }
            if(false !== $result || 0 !== $result){
                //操作日志
                $this->Orderlog->create([
                    'order_id'=>$row->id,
                    'dep_name'=>Session::get('admin.department_text'),
                    'dep_id'=>Session::get('admin.department'),
                    'userid'=> Session::get('admin.userid'),
                    'username'=>Session::get('admin.username'),
                    'content'=>$status == 1 ? '审核通过处理':'订单作废处理',
                    'type'=>1, //1审核状态  2出入库状态
                ]);
                $this->success();
            }else{
                $this->error();
            }
        }
    }

    /**
     * 修改备注
     * @param null $ids
     */
    public function remark($ids=null)
    {
        $row = $this->model->get($ids);
        $row->remark = $this->request->request('remark','');
        $result = $row->save();
        if ($result !== false) {
            //操作日志
            $this->Orderlog->create([
                'order_id'=>$row->id,
                'dep_name'=>Session::get('admin.department_text'),
                'dep_id'=>Session::get('admin.department'),
                'userid'=> Session::get('admin.userid'),
                'username'=>Session::get('admin.username'),
                'content'=>'修改备注['.$this->request->request('remark','').']',
                'type'=>1, //1审核状态  2出入库状态
            ]);
            $this->success('修改备注成功');
        } else {
            $this->error($row->getError());
        }
    }

    /**
     * 修改订单数量
     * @param null $ids
     */
    public function editNum($ids=null)
    {
        if($this->request->isAjax('POST'))
        {
            $row = $this->Orderitem->get($ids);
            $row->num = $this->request->request('number');
            $result = $row->save();
            if ($result !== false) {
                //操作日志
                $this->Orderlog->create([
                    'order_id'=>$row->order_id,
                    'dep_name'=>Session::get('admin.department_text'),
                    'dep_id'=>Session::get('admin.department'),
                    'userid'=> Session::get('admin.userid'),
                    'username'=>Session::get('admin.username'),
                    'content'=>'修改数量产品ID'.$row->preproduct_id.'数量['.$row->num.']',
                    'type'=>1, //1审核状态  2出入库状态
                ]);
                $this->success('修改成功！');
            } else {
                $this->error('修改失败！');
            }
        }
        $this->error('请求错误！');
    }

    /**
     * 发货 填写物流单号
     * @param null $ids
     * @return string
     * @throws \think\Exception
     */
    public function edit($ids = NULL)
    {
        $model = new Details();
        $row = $model->get($ids);
        if (!$row)
            $this->error(__('No Results were found'));
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            $params['status'] = 1;
            if ($params) {
                $result = $row->allowField(true)->save($params);
                if ($result !== false) {
                    $this->success("操作成功！<script>window.location.reload();</script>");
                } else {
                    $this->error($row->getError());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /**
     * 订单详情删除
     */
    public function delItem($ids = "")
    {
        if ($ids) {
            $pk = $this->Orderitem->getPk();
            $adminIds = $this->getDataLimitAdminIds();
            if (is_array($adminIds)) {
                $count = $this->Orderitem->where($this->dataLimitField, 'in', $adminIds);
            }
            $row = $this->Orderitem->get($ids);
            $list = $this->Orderitem->where($pk, 'in', $ids)->select();
            $count = 0;
            foreach ($list as $k => $v) {
                $count += $v->delete();
            }
            if ($count) {
                //操作日志
                $this->Orderlog->create([
                    'order_id'=>$row->order_id,
                    'dep_name'=>Session::get('admin.department_text'),
                    'dep_id'=>Session::get('admin.department'),
                    'userid'=> Session::get('admin.userid'),
                    'username'=>Session::get('admin.username'),
                    'content'=>'删除产品ID'.$row->preproduct_id.'数量['.$row->num.']',
                    'type'=>1, //1审核状态  2出入库状态
                ]);
                $this->success();
            } else {
                $this->error(__('No rows were deleted'));
            }
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }



}
